package com.haircut.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haircut.base.Result;
import com.haircut.enums.UserType;
import com.haircut.exception.BusinessException;
import com.haircut.mapper.WechatUser;
import com.haircut.mapper.WechatUserMapper;
import com.haircut.model.dto.UserDTO;
import com.haircut.model.dto.UserListDto;
import com.haircut.model.page.PageParam;
import com.haircut.model.req.RemarkReq;
import com.haircut.security.model.WxAuthenticationToken;
import com.haircut.security.model.SysUserDetails;
import com.haircut.security.model.WxLoginRequest;
import com.haircut.security.model.WxLoginResult;
import com.haircut.service.WechatUserService;
import com.haircut.security.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class WechatUserServiceImpl extends ServiceImpl<WechatUserMapper, WechatUser> implements WechatUserService {


    private final JwtUtil jwtUtil;
    private final AuthenticationManager authenticationManager;

    @Override
    public WxLoginResult loginByWechat(String mobile, String wxOpenid) {
        // 认证用户信息
        WxAuthenticationToken authenticationToken = new WxAuthenticationToken(mobile, wxOpenid);
        // 认证
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        // 认证成功，生成Token
        String accessToken = jwtUtil.createToken(authentication);

        SysUserDetails userDetails = (SysUserDetails) authentication.getPrincipal();
        Long userId = userDetails.getUserId();
//        checkUserAccount(wxOpenid);
        return WxLoginResult.builder()
                .tokenType("Bearer")
                .accessToken(accessToken)
                .build();
    }

    @Override
    public Result<String> register(String phone) {

        WechatUser user = getByPhone(phone);

        if(user == null){
            //注册到用户
            WechatUser newUser = new WechatUser();
            newUser.setPhone(phone);
            newUser.setUserType(UserType.CUSTOMER.getCode());
            newUser.setNickname("顾客"+phone.substring(7));
            newUser.setBalance(BigDecimal.ZERO);

            int result = baseMapper.insert(newUser);
            if(result == 1){
                return Result.success();
            }
        }

        return Result.failed("");
    }

    @Override
    public boolean updateUserType(Long userId, String userType) {
        // 校验角色合法性
        if (!"ADMIN".equals(userType) && !"BARBER".equals(userType) && !"CUSTOMER".equals(userType)) {
            throw new BusinessException("无效的角色类型");
        }
        WechatUser user = new WechatUser();
        user.setId(userId);
        user.setUserType(userType);
        return baseMapper.updateById(user) > 0;
    }
//    private void checkUserAccount(String wxOpenid) {
//        //用户账户
//        WechatUser user = getOne(new LambdaQueryWrapper<WechatUser>()
//                .eq(WechatUser::getOpenid, wxOpenid)
//                .select(
//                        WechatUser::getId,
//                        WechatUser::getNickname,
//                        WechatUser::getAvatar
//                )
//        );
//        SysUserAccount userAccount = userAccountService.getById(user.getId());
//        if (userAccount == null){
//            userAccountService.createUserAccount(user.getId());
//        }
//
//        checkUserPromotionId(user);
//    }


    // 创建新用户（默认客户角色）
    @Override
    public WechatUser createNewUser(String openid, String mobile) {
        WechatUser user = new WechatUser();
        user.setOpenid(openid);
        user.setAvatar(mobile);
        user.setUserType("CUSTOMER");  // 默认客户角色
        user.setStatus(1);  // 启用状态
        return baseMapper.insert(user) > 0 ? user : null;
    }

    @Override
    public WechatUser getByOpenid(String wxOpenid) {
        LambdaQueryWrapper<WechatUser> eq = new LambdaQueryWrapper<WechatUser>().eq(WechatUser::getOpenid, wxOpenid);
        return baseMapper.selectOne(eq);
    }


    @Override
    public UserDetails loadUserByWxOpenid(String mobile, String wxOpenid) {
        SysUserDetails sysUserDetails = new SysUserDetails();
        WechatUser wechatUser = getByOpenid(wxOpenid);
        sysUserDetails.setUserId(wechatUser.getId());
        sysUserDetails.setOpenId(wxOpenid);
        return sysUserDetails;
    }

    @Override
    public WechatUser getByPhone(String phone) {
        LambdaQueryWrapper<WechatUser> queryWrapper = new LambdaQueryWrapper<WechatUser>().eq(WechatUser::getPhone, phone);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public Result<UserListDto> userList(PageParam req) {
        log.info("userList"+req.getPageNum() + "-" + req.getPageSize(),"");

        UserListDto dto = new UserListDto();
        Page<WechatUser> page = new Page<>(req.getPageNum(), req.getPageSize());
        QueryWrapper<WechatUser> wrapper = new QueryWrapper<>();
        Page<WechatUser> result = baseMapper.selectPage(page, wrapper);
        List<UserDTO> userModels = result.getRecords().stream()
                .map(user -> {
                    UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
                    userDTO.setName(user.getNickname());
                    return userDTO;
                })
                .collect(Collectors.toList());
        dto.setUserList(userModels);
        dto.setTotal(result.getTotal());
        return Result.success(dto);
    }

    @Override
    public Result<UserDTO> singleUser(String phone) {
        WechatUser user = baseMapper.selectOne(new LambdaQueryWrapper<WechatUser>().eq(WechatUser::getPhone, phone));
        UserDTO dto = BeanUtil.copyProperties(user,UserDTO.class);
        if(dto == null){
            return Result.failed("手机号暂未注册");
        }else{
            dto.setName(user.getNickname());
            return Result.success(dto);
        }
    }

    @Override
    public void updateUserInfo(Long userId, String avatarUrl, String nickName) {
        WechatUser wechatUser = getById(userId);
        if(ObjectUtil.isNull(wechatUser)){
            throw new BusinessException("用户不存在");
        }
        WechatUser updateWeChatUser = new WechatUser();
        updateWeChatUser.setId(userId);
        updateWeChatUser.setNickname(nickName);
        updateWeChatUser.setAvatar(avatarUrl);
        updateById(updateWeChatUser);
    }

    @Override
    public Result<String> addRemark(RemarkReq req) {
        if(ObjectUtil.isEmpty(req.getRemark()) || ObjectUtil.isEmpty(req.getPhone()) || ObjectUtil.isEmpty(req.getRealName())){
            return Result.failed("请输入手机号,姓名和备注");
        }
        WechatUser wechatUserUpdate = new WechatUser();
        wechatUserUpdate.setPhone(req.getPhone());
        wechatUserUpdate.setRemark(req.getRemark());
        updateById(wechatUserUpdate);
        UpdateWrapper<WechatUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(WechatUser::getPhone,req.getPhone())
        .set(WechatUser::getRemark, req.getRemark())
        .set(WechatUser::getRealName, req.getRealName());
        boolean flag = update(updateWrapper);
        if(flag){
            return Result.success();
        }else{
            return Result.failed("更改备注失败");
        }
    }
}